import { _decorator } from "cc";
import { eventDispatcher, TILE_HEIGHT, TILE_WIDTH } from "../Constants";
import { Entity } from "./Entity";
import { EventType } from "../enums/EventType";
import { Direction } from "../enums/Direction";
const { ccclass } = _decorator;

@ccclass("Burst")
export class Burst extends Entity {

    protected registerEvents(): void {
        eventDispatcher.on(EventType.PLAYER_MOVE_END, this.onPlayerMove, this);
        eventDispatcher.on(EventType.PLAYER_ROTATE_END, this.onPlayerRotate, this);
    }

    public updatePosition(): void {
        this.node.setPosition(this.x * TILE_WIDTH, -this.y * TILE_HEIGHT);
    }

    private onPlayerMove(x: number, y: number, lastX: number, lastY: number): void {
        if (this.state === Entity.State.DEATH) {
            return;
        }

        if (this.state === Entity.State.IDLE && x === this.x && y === this.y) {
            this.state = Entity.State.ATTACK;
        } else if (this.state === Entity.State.ATTACK && lastX === this.x && lastY === this.y) {
            this.state = Entity.State.DEATH;
        }
    }

    private onPlayerRotate(x: number, y: number): void {
        if (this.state === Entity.State.DEATH) {
            return;
        }

        if (this.state === Entity.State.ATTACK && x === this.x && y === this.y) {
            this.state = Entity.State.DEATH;
            eventDispatcher.emit(EventType.ATTACK_PLAYER, 1);
            eventDispatcher.emit(EventType.SCENE_SHAKE, Direction.BOTTOM);
        }
    }
}